package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.cloudbroker.bcs.platform.dav.middle.util.ViewpointMsgFormatUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.DateTimeUtil;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSFields;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.HSBCPSVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.history.HistoryBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.history.result.HistoryListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.history.result.HistoryListDataForSearch;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.history.result.HistoryListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.history.result.HistorySearchEngineStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.service.viewpoint.vo.HistoryRecordForm;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.constant.SysContants;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.Answer;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.entity.Customer;
import com.cloudbroker.bcs.platform.dav.middle.entity.Question;
import com.cloudbroker.bcs.platform.dav.middle.entity.RollingMsg;
import com.cloudbroker.bcs.platform.dav.middle.entity.ViewpointMsg;
import com.cloudbroker.bcs.platform.dav.middle.entityview.HistoryListDataView;
import com.cloudbroker.bcs.platform.dav.middle.service.AnswerService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerService;
import com.cloudbroker.bcs.platform.dav.middle.service.QuestionService;
import com.cloudbroker.bcs.platform.dav.middle.service.RollingMsgService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointMsgService;
import com.cloudbroker.bcs.platform.dav.middle.util.SearchUtil;
import com.cloudbroker.bsc.common.search.common.SearchEngineAdapterClient;

/**
 * Created by zhaojp18008 on 2016/5/9.
 */
@Service
public class HistoryBizServiceImpl implements HistoryBizService {
    
    @Resource
    private ViewpointMsgService viewpointMsgService;
    
    @Resource
    private RollingMsgService rollingMsgService;
    
    @Resource
    private QuestionService questionService;
    
    @Resource
    private BrokerService brokerService;
    
    @Resource
    private AnswerService answerService;
    
    @Resource
    private CustomerService customerService;
    
    private static final String TABLE_NAME = "history";
    private static final String QUESTION_TABLE_PREFIX = "question_";
    private static final String VIEWPOINT_TABLE_PREFIX = "viewpoint_";
    private static final String ROLLINGMSG_TABLE_PREFIX = "rollingmsg_";
    public static final Integer QUESTION_TYPE = 0;
    public static final Integer ROLLINGMSG_TYPE = 1;
    public static final Integer VIEWPOINT_TYPE = 2;
    
    private static final Logger logger = LoggerFactory.getLogger(HistoryBizServiceImpl.class);
    
    // 搜索引擎状态获取
    @Override
    public HistorySearchEngineStatus funSearchEngineStatus(HSBCPSVO param){
    	
    	HistorySearchEngineStatus historySearchEngineStatus = new HistorySearchEngineStatus();
    	Boolean searchEngine_enable = ConfigValues.getSearchEngineEnable();
        Integer status = 0;     	
    	if(searchEngine_enable){
    		status = 0;
    	}else{
    		status = 1;
    	}
    	historySearchEngineStatus.setSearch_engine_flag(status);
		return VOUtil.setSuccessResult(historySearchEngineStatus);
    }
    
    
    @Override
    public HistoryListResult funcHistoryRecordList(HistoryRecordForm param) {
        HistoryListResult historyListResult = new HistoryListResult();
        Long broker_id = HSBCPSBizDataContext.getBrokerId();
        if (null == broker_id) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, HistoryListResult.class);
        }
        String ker_word = param.getKey_word().trim();
        String start_time = param.getStart_time();
        String end_time = param.getEnd_time();
        if (StringUtil.isEmpty(end_time)) {
            end_time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        }
        Integer request_num = Integer.parseInt(param.getRequest_num());
        if (null == request_num || request_num < SysContants.MIN_REQUEST_NUM
                || request_num > SysContants.MAX_REQUEST_NUM) {
            request_num = SysContants.DEFAULT_REQUSET_NUM;
        }
        String position_str = param.getPosition_str();
        String qry_type = param.getQry_type();
        Map params = new HashMap();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
       
        if ("3".equals(qry_type)) {
            //历史查询全部数据检索
            params.put(HSBCPSFields.BROKER_ID, "es equals " + broker_id);
            if (!StringUtil.isEmpty(ker_word)) {
                params.put("orCondition", "es should content == " + ker_word + " or broker_name == " + ker_word
                        + " or customer_name == " + ker_word + " or answer_content == " + ker_word
                        + " or label == " + ker_word + " or tag_name == " + ker_word);
            }
            Long position_strStart = Long.valueOf(position_str);
            Long position_strEnd = (long) 0;
            if (position_strStart != 0) {
            	//position_strStart-5 搜索引擎LONG型太长精度丢失  -5查询保证查询结果
                params.put("position_str_long", "es range " + position_strEnd + " " + (position_strStart-5));
            }
            List<Map> listSearch = SearchEngineAdapterClient.getSearchEngineAdapter().query("history", params, 0,
                    request_num, "position_str_long", "desc");
            System.out.println(listSearch);
            if (listSearch != null && listSearch.size() > 0) {
                for (Map map : listSearch) {
                    list.add(map);
                }
            }
        } else {
            params.put(HSBCPSFields.TENANT_ID, HSBCPSBizDataContext.getTenantId());
            params.put(HSBCPSFields.BROKER_ID, broker_id);
            params.put(HSBCPSFields.POSITION_STR, position_str);
            params.put(HSBCPSFields.START_TIME, start_time);
            params.put(HSBCPSFields.END_TIME, end_time);
            params.put(HSBCPSFields.REQUEST_NUM, request_num);
            List<HistoryListDataView> viewList = null;
            if ("2".equals(qry_type)) {
                // 观点列表历史查询
                params.put(HSBCPSFields.VIEWPOINT_CONTENT, ker_word);
                viewList = viewpointMsgService.qryHistoryRecord(params);
            } else if ("0".equals(qry_type)) {
                // 问与答历史查询
                params.put("question_content", ker_word);
                viewList = questionService.qryHistoryRecord(params);
            } else if ("1".equals(qry_type)) {
                params.put("msg_content", ker_word);
                viewList = rollingMsgService.qryHistoryRecord(params);
            }
            historyListResult.newDataList().addAll(viewList);
            return VOUtil.setSuccessResult(historyListResult);
        }
        
        if (null != list && list.size() > 0) {
            List<HistoryListData> historyListDatas = new ArrayList<>();
            for (Map<String, Object> map : list) {
                HistoryListData historyListData = new HistoryListData();
              if ("3".equals(qry_type)) {
                    historyListData.setBroker_avatar(ValueUtil.getString(map.get("broker_avatar")));
                    historyListData.setBroker_name(ValueUtil.getString(map.get("broker_name")));
                    historyListData.setInfo_type(ValueUtil.getInt(map.get("info_type")));
                    historyListData.setId(ValueUtil.getLong(map.get("id")));
                    historyListData.setLabel(ValueUtil.getString(map.get("label")));
                    historyListData.setTag_name(ValueUtil.getString(map.get("tag_name")));
                    historyListData.setImg_audio(ValueUtil.getString(map.get("img_audio")));
                    historyListData.setPosition_str(ValueUtil.getString(map.get("position_str_long")));
                    historyListData.setContent(ValueUtil.getString(map.get("content")));
                    String content = ValueUtil.getString(map.get("content"));
                    historyListData.setContent(ViewpointMsgFormatUtil.parseContext(content));
                    historyListData.setTag_id(ValueUtil.getString(map.get("tag_id")));
                    historyListData.setAnswer_content(ValueUtil.getString(map.get("answer_content")));
                    historyListData.setAnswer_tag(ValueUtil.getString(map.get("answer_tag")));
                    historyListData.setCustomer_name(ValueUtil.getString(map.get("customer_name")));
                    historyListData.setAvatar(ValueUtil.getString(map.get("customer_avatar")));
                    historyListData.setBroker_id(broker_id);
                    historyListData.setSend_time(ValueUtil.getString(map.get("send_time")));
                    historyListData.setAnswer_time(ValueUtil.getString(map.get("answer_time")));
                }
                historyListDatas.add(historyListData);
            }
            historyListResult.setData_list(historyListDatas);
            return VOUtil.setSuccessResult(historyListResult);
        } else {
            return VOUtil
                    .genErrorResult(HSBCPSErrorCodes.SysMgtErr.NO_SUCH_HISTORY_RECORD, HistoryListResult.class);
        }
    }
    
    /**
     * 仅供数据库数据导入搜索引擎使用
     */
    @Override
    public HSBCPSBackVO funcImportSearchEngine(HSBCPSVO param) {
        
        Object Results = SearchUtil.getInstance().deleteAll();
        HSBCPSBackVO result = new HSBCPSBackVO();
        if (Results != null) {
        	Runnable r = new Runnable() {
				@Override
				public void run() {
//					 观点列表导入开始
	                logger.error("观点列表导入开始");
	                List<ViewpointMsg> list = viewpointMsgService.qryHistoryRecordForSearch();
	                if (list != null) {
	                    for (ViewpointMsg msg : list) {
	                        HistoryListDataForSearch data = new HistoryListDataForSearch();
	                        data.setId(ValueUtil.getLong(msg.getViewpoint_id()));
	                        data.setImg_audio(ValueUtil.getString(msg.getViewpoint_img_audio()));
	                        data.setBroker_id(ValueUtil.getLong(msg.getBroker_id()));
	                        data.setContent(ValueUtil.getString(msg.getViewpoint_content()));
	                        data.setLabel(ValueUtil.getString(msg.getViewpoint_abstract()));
	                        if (msg.getViewpoint_tag() != null) {
	                            data.setTag_id(String.valueOf(msg.getViewpoint_tag()));
	                        }
	                        data.setTag_name(ValueUtil.getString(msg.getViewpoint_tag_name()));
	                        String send_time = DateTimeUtil.toString(msg.getSend_time(),
	                                DateTimeUtil.FORMAT_YYYYMMDDHHMMSSSSS_NO_BREAK);
	                        data.setSend_time(send_time);
                            data.setPublic_flag(ValueUtil.getString(msg.getViewpoint_type()));
                            data.setPublic_review_status(msg.getViewpoint_public_status());
	                        data.setPositionStrByTime(msg.getPosition_str());
	                        Broker broker = brokerService.get(msg.getBroker_id().toString());
	                        if(broker!=null){
	                        	data.setBroker_name(ValueUtil.getString(broker.getBroker_name(),"0"));
		                        data.setBroker_avatar(ValueUtil.getString(broker.getBroker_avatar()));
	                        }
	                        data.setInfo_type(VIEWPOINT_TYPE);
	                        SearchEngineAdapterClient.getSearchEngineAdapter().save(TABLE_NAME,
	                                VIEWPOINT_TABLE_PREFIX + ValueUtil.getLong(msg.getViewpoint_id()), data);
	                    }
	                }
	                logger.error("观点列表导入结束");
	                logger.error("问与答导入开始");
	                List<Question> qlist = questionService.qryHistoryRecordForSearch();
	                if (qlist != null) {
	                    for (Question q : qlist) {
	                        Answer answer = answerService.queryAnswerByQuestionId(ValueUtil.getLong(q.getQuestion_id()));
	                        HistoryListDataForSearch data = new HistoryListDataForSearch();
	                        data.setId(ValueUtil.getLong(q.getQuestion_id()));
	                        data.setTag_id(ValueUtil.getString(q.getQuestion_tag()));
	                        data.setContent(ValueUtil.getString(q.getQuestion_content()));
	                        data.setSend_time(DateTimeUtil.toString(q.getCreate_time(),
	                                DateTimeUtil.FORMAT_YYYYMMDDHHMMSSSSS_NO_BREAK));
	                        data.setPositionStrByTime(q.getPosition_str());
	                        Customer customer = customerService.get(ValueUtil.getString(q.getCustomer_id().toString()));
	                        if(customer != null){
	                        	if(customer.getCustomer_name()!=null){
	                        		data.setCustomer_name(ValueUtil.getString(customer.getCustomer_name()));
	                        	}
	                        }
	                        data.setAnswer_tag(ValueUtil.getString(answer.getAnswer_tag()));
	                        data.setAnswer_content(ValueUtil.getString(answer.getAnswer_content()));
	                        data.setAnswer_time(DateTimeUtil.toString(answer.getCreate_time(),
	                                DateTimeUtil.FORMAT_YYYYMMDDHHMMSSSSS_NO_BREAK));
	                        Broker broker = brokerService.get(ValueUtil.getString(q.getBroker_id()));
	                        if(broker!=null){
	                        	if(broker.getBroker_name()!=null){
	                        		data.setBroker_name(ValueUtil.getString(broker.getBroker_name()));
	                        	}
	                        	if(broker.getBroker_avatar()!=null){
	                        		data.setBroker_avatar(ValueUtil.getString(broker.getBroker_avatar()));
	                        	}
	                        }
	                        data.setBroker_id(ValueUtil.getLong(q.getBroker_id()));
	                        data.setInfo_type(QUESTION_TYPE);
	                        SearchEngineAdapterClient.getSearchEngineAdapter().save(TABLE_NAME,
	                                QUESTION_TABLE_PREFIX + ValueUtil.getLong(q.getQuestion_id()), data);
	                    }
	                }
	                logger.error("问与答导入结束");
	                logger.error("实时列表导入开始");
	                List<RollingMsg> rlist = rollingMsgService.qryHistoryRecordForSearch();
	                if (rlist != null) {
	                    for (RollingMsg m : rlist) {
	                        Broker broker = brokerService.get(ValueUtil.getString(m.getBroker_id().toString()));
	                        HistoryListDataForSearch data = new HistoryListDataForSearch();
	                        data.setBroker_id(ValueUtil.getLong(m.getBroker_id()));
	                        data.setSend_time(DateTimeUtil.toString(m.getCreate_time(),
	                                DateTimeUtil.FORMAT_YYYYMMDDHHMMSSSSS_NO_BREAK));
	                        data.setPositionStrByTime(m.getPosition_str());
	                        data.setContent(ValueUtil.getString(m.getMsg_content()));
	                        data.setId(ValueUtil.getLong(m.getRollingmsg_id()));
	                        if (broker != null) {
	                            if (broker.getBroker_name() != null) {
	                                data.setBroker_name(broker.getBroker_name());
	                            }
	                            if (broker.getBroker_avatar() != null) {
	                                data.setBroker_avatar(broker.getBroker_avatar());
	                            }
	                        }
	                        data.setInfo_type(ROLLINGMSG_TYPE);
	                        boolean s = SearchEngineAdapterClient.getSearchEngineAdapter().save(TABLE_NAME,
	                                ROLLINGMSG_TABLE_PREFIX + ValueUtil.getLong(m.getRollingmsg_id()), data);
	                    }
	                }
	                logger.error("实时列表导入结束");
	                logger.error("历史数据导入结束");
				}
			};
			Thread t = new Thread(r);
			t.start();
        }
        return VOUtil.setSuccessResult(result);
        
    }
}
